package com.itboye.textileexpres.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import com.itboye.textileexpres.R;
import com.itboye.textileexpres.base.MainApplication;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import android.content.Context;
import android.graphics.Bitmap.Config;
import android.widget.ImageView;

/**
 * 鍩轰簬 OKhttp鐨処mageLoader
 * 
 * @author Young
 * 
 */
public class XImageLoader {

	static {
		long maxMamory = Runtime.getRuntime().maxMemory();// 搴旂敤绋嬪簭绋嬪簭杩愯鏃舵墍浣跨敤鏈�澶у唴瀛樻暟
		maxMamory = (long) (maxMamory * 0.7);
		int v = Runtime.getRuntime().availableProcessors();
		int availableProcessors = v < 4 ? 3 : v - 1;

		// System.out.println("maxMamory : " + maxMamory +
		// "  availableProcessors: " + availableProcessors);

		// DebugToast.show("maxMamory : " + (maxMamory/1024.0f/1024 )+
		// "  availableProcessors: " + availableProcessors, 1);

		DisplayImageOptions options = new DisplayImageOptions.Builder()
				// 璁剧疆鍥剧墖涓嬭浇鏈熼棿鏄剧ず鐨勫浘鐗�
				.showImageOnLoading(R.drawable.defaultshow)
				.showImageForEmptyUri(R.drawable.defaultshow)// 璁剧疆鍥剧墖Uri涓虹┖鎴栨槸閿欒鐨勬椂鍊欐樉绀虹殑鍥剧墖
				.showImageOnFail(R.drawable.defaultshow) // 璁剧疆鍥剧墖鍔犺浇鎴栬В鐮佽繃绋嬩腑鍙戠敓閿欒鏄剧ず鐨勫浘鐗�
				.cacheInMemory(true)// 璁剧疆涓嬭浇鐨勫浘鐗囨槸鍚︾紦瀛樺湪鍐呭瓨涓�
				.cacheOnDisk(true)// 璁剧疆涓嬭浇鐨勫浘鐗囨槸鍚︾紦瀛樺湪SD鍗′腑
				.bitmapConfig(Config.RGB_565)
				// .displayer(new RoundedBitmapDisplayer(20))// 璁剧疆鎴愬渾瑙掑浘鐗�
				.build(); // 鍒涘缓閰嶇疆杩囧緱DisplayImageOption瀵硅薄聽

		// File cacheDir = StorageUtils.getOwnCacheDirectory(App.ctx,
		// "sunsun/Cache");
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				MainApplication.context)
				.memoryCacheExtraOptions(480, 800)
				// max width, max
				// height锛屽嵆淇濆瓨鐨勬瘡涓紦瀛樻枃浠剁殑鏈�澶ч暱瀹�
				// .discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75,
				// null) // Can slow ImageLoader, use it carefully (Better don't
				// use it)/璁剧疆缂撳瓨鐨勮缁嗕俊鎭紝鏈�濂戒笉瑕佽缃繖涓�
				.threadPoolSize(availableProcessors)
				// 绾跨▼姹犲唴鍔犺浇鐨勬暟閲�
				.threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				// .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 *
				// 1024)) // You can pass your own memory cache
				// implementation/浣犲彲浠ラ�氳繃鑷繁鐨勫唴瀛樼紦瀛樺疄鐜�
				// .memoryCache(new WeakMemoryCache())

				.memoryCacheSize((int) maxMamory)
				// .memoryCacheSize(15 * 1024 * 1024)

				.diskCacheSize(80 * 1024 * 1024)
				.diskCacheFileNameGenerator(new Md5FileNameGenerator())// 灏嗕繚瀛樼殑鏃跺�欑殑URI鍚嶇О鐢∕D5
																		// 鍔犲瘑

				.tasksProcessingOrder(QueueProcessingType.LIFO) // 鍚庤繘鍏堝嚭
				// .diskCacheFileCount(100) //缂撳瓨鐨勬枃浠舵暟閲�
				// .diskCache(new UnlimitedDiscCache(cacheDir))//鑷畾涔夌紦瀛樿矾寰�
				// .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
				.defaultDisplayImageOptions(options)
				// .imageDownloader(new BaseImageDownloader(App.ctx, 5 * 1000,
				// 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)瓒呮椂鏃堕棿
				.imageDownloader(
						new DownloadImageFromNetWork(MainApplication.context,
								5 * 1000, 30 * 1000)).writeDebugLogs() // Remove
				// for
				// release
				// app
				.build();// 寮�濮嬫瀯寤�
		// Initialize ImageLoader with configuration.

		com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(
				config);// 鍏ㄥ眬鍒濆鍖栨閰嶇疆

	}

	private static class DownloadImageFromNetWork extends BaseImageDownloader {

		public DownloadImageFromNetWork(Context context, int connectTimeout,
				int readTimeout) {
			super(context, connectTimeout, readTimeout);
		}

		@Override
		protected InputStream getStreamFromNetwork(String arg0, Object arg1)
				throws IOException {

			try {
				OkHttpClient client = new OkHttpClient();
				client.setConnectTimeout(connectTimeout, TimeUnit.MILLISECONDS);
				client.setReadTimeout(readTimeout, TimeUnit.MILLISECONDS);
				Request request = new Request.Builder().url(arg0).build();
				Response response = client.newCall(request).execute();
				if (!response.isSuccessful()) {
					return null;
				} else {
					return response.body().byteStream();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}

	}

	/**
	 * 鍔犺浇缃戠粶鍥剧墖
	 * 
	 * @param uri
	 * @param imageView
	 */
	public static void load(String uri, ImageView imageView) {

		ImageLoader.getInstance().displayImage(uri, imageView);

		DebugLog.v("downloadImg", "" + uri);
	}
}
